<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>编辑邮箱配置</title>
    <link rel="stylesheet" href="../../../component/pear/css/pear.css" />
    <style>
        .mainBox { padding: 15px; }
        .main-container { max-width: 800px; margin: 0 auto; }
        .layui-form-item { margin-bottom: 20px; }
        .bottom { position: fixed; bottom: 0; left: 0; right: 0; padding: 15px; 
                  background: #fff; box-shadow: 0 -2px 10px rgba(0,0,0,0.05); }
        .button-container { text-align: center; }
        .button-container button { margin: 0 8px; }
    </style>
</head>

<body>
    <form class="layui-form" action="" lay-filter="email-edit-huixian">
        <div class="mainBox">
            <div class="main-container">
                <!-- 配置名称（必填） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">配置名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="name" id="name" lay-verify="required|verifyName" 
                               autocomplete="off" placeholder="请输入配置名称（如：企业QQ邮箱）" 
                               class="layui-input">
                    </div>
                </div>

                <!-- SMTP服务器（必填） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">SMTP</label>
                    <div class="layui-input-block">
                        <input type="text" name="email_host" id="email_host" lay-verify="required|verifyHost" 
                               autocomplete="off" placeholder="请输入SMTP地址（如：smtp.qq.com）" 
                               class="layui-input">
                    </div>
                </div>

                <!-- SMTP端口（必填） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">SMTP端口</label>
                    <div class="layui-input-block">
                        <input type="text" name="email_port" id="email_port" lay-verify="required|verifyPort" 
                               autocomplete="off" placeholder="常用：465(SSL)、587(非SSL)" 
                               class="layui-input">
                    </div>
                </div>

                <!-- 邮箱账号（必填） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">邮箱账号</label>
                    <div class="layui-input-block">
                        <input type="text" name="email_user" id="email_user" lay-verify="required|verifyEmail" 
                               autocomplete="off" placeholder="请输入发送邮件的邮箱（如：xxx@qq.com）" 
                               class="layui-input">
                    </div>
                </div>

                <!-- 授权码/密码（非必填：为空则不更新） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">授权码/密码</label>
                    <div class="layui-input-block">
                        <input type="text" name="email_password" id="email_password" lay-verify="verifyPwdLength" 
                               autocomplete="off" placeholder="不修改请留空（修改请输入新授权码）" 
                               class="layui-input">
                    </div>
                </div>

                <!-- 是否使用SSL（单选：1=是，0=否） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">使用SSL</label>
                    <div class="layui-input-block">
                        <input type="radio" name="use_ssl" value="1" title="是" lay-skin="tag">
                        <input type="radio" name="use_ssl" value="0" title="否" lay-skin="tag">
                    </div>
                </div>

                <!-- 是否默认配置（单选：1=是，0=否） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">默认配置</label>
                    <div class="layui-input-block">
                        <input type="radio" name="is_default" value="1" title="是" lay-skin="tag">
                        <input type="radio" name="is_default" value="0" title="否" lay-skin="tag">
                    </div>
                </div>

                <!-- 配置状态（单选：1=开启，0=关闭） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">配置状态</label>
                    <div class="layui-input-block">
                        <input type="radio" name="is_active" value="1" title="开启" lay-skin="tag">
                        <input type="radio" name="is_active" value="0" title="关闭" lay-skin="tag">
                    </div>
                </div>

                <!-- 排序号（非负整数） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">排序号</label>
                    <div class="layui-input-block">
                        <input type="text" name="sort_num" id="sort_num" lay-verify="verifySort" 
                               autocomplete="off" placeholder="数字越大，列表中越靠前" 
                               class="layui-input">
                    </div>
                </div>
            </div>
        </div>

        <!-- 底部提交按钮区域 -->
        <div class="bottom">
            <div class="button-container">
                <button type="submit" class="pear-btn pear-btn-primary pear-btn-sm" 
                        lay-submit lay-filter="email-config-save">
                    <i class="layui-icon layui-icon-ok"></i>
                    提交
                </button>
                <button type="button" class="pear-btn pear-btn-danger pear-btn-sm" id="close-btn">
                    <i class="layui-icon layui-icon-close"></i>
                    关闭
                </button>
            </div>
        </div>
    </form>

    <!-- 引入依赖JS文件 -->
    <script src="../../../component/com/api.js"></script>
    <script src="../../../component/com/auth.js"></script>
    <script src="../../../component/layui/layui.js"></script>
    <script src="../../../component/pear/pear.js"></script>
    <script>
        layui.use(['form', 'jquery', 'layer'], function () {
            let form = layui.form;
            let $ = layui.jquery;
            let layer = layui.layer;
            
            // 基础配置
            const API_BASE_URL = apiConfig.baseUrl;
            const AUTH_TOKEN = window.localStorage.getItem("token") || window.sessionStorage.getItem("token");
            const urlParams = new URLSearchParams(window.location.search);
            const CONFIG_ID = urlParams.get('id'); // 编辑的配置ID
            let initialData = {}; // 存储初始数据（用于对比变更）

            // 1. 加载配置详情并回显表单
            if (CONFIG_ID) {
                loadEmailConfig();
            } else {
                layer.msg('配置ID不存在，无法编辑', { icon: 2, time: 2000 });
                setTimeout(() => parent.layer.close(parent.layer.getFrameIndex(window.name)), 2000);
            }

            // 加载配置详情的核心函数
            function loadEmailConfig() {
                const loading = layer.load(2, { shade: 0.3 });
                $.ajax({
                    url: `${API_BASE_URL}/email/config/${CONFIG_ID}/`, // 统一接口前缀（与列表页一致）
                    dataType: 'json',
                    type: 'GET',
                    headers: { "Authorization": AUTH_TOKEN },
                    success: function (result) {
                        layer.close(loading);
                        if (result.success && result.data) {
                            const data = result.data;
                            // 保存初始数据（深拷贝，确保类型为字符串，便于对比）
                            initialData = {
                                name: data.name || '',
                                email_host: data.email_host || '',
                                email_port: data.email_port.toString() || '0',
                                email_user: data.email_user || '',
                                email_password: data.email_password || '',
                                use_ssl: data.use_ssl.toString() || '0', // 后端是IntegerField，转字符串
                                is_default: data.is_default.toString() || '0', // 后端是IntegerField，转字符串
                                is_active: data.is_active.toString() || '1',
                                sort_num: data.sort_num.toString() || '0'
                            };

                            // 回显表单（关键：与单选框value值匹配，确保选中状态正确）
                            form.val("email-edit-huixian", initialData);
                            // 重新渲染表单（解决单选框回显后不选中的问题）
                            form.render();
                        } else {
                            const errorMsg = result.message || '加载配置失败';
                            layer.msg(errorMsg, { icon: 2, time: 2000 });
                        }
                    },
                    error: function (xhr) {
                        layer.close(loading);
                        const errorMsg = xhr.status === 401 ? '登录已过期，请重新登录' : '网络异常，加载失败';
                        layer.msg(errorMsg, { icon: 2, time: 2000 });
                        if (xhr.status === 401) parent.window.location.href = '../../../login.html';
                    }
                });
            }

            // 2. 表单验证规则（适配IntegerField类型）
            form.verify({
                verifyName: function (value) {
                    const trimValue = value.trim();
                    if (trimValue.length === 0) return "配置名称不能为空";
                    if (trimValue.length > 100) return "配置名称长度不能超过100个字符";
                },
                verifyHost: function (value) {
                    if (value.trim().length === 0) return "SMTP服务器地址不能为空";
                },
                verifyPort: function (value) {
                    const port = parseInt(value);
                    if (isNaN(port) || port < 1 || port > 65535) return "请输入1-65535之间的有效端口";
                },
                verifyEmail: function (value) {
                    const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
                    if (!emailReg.test(value.trim())) return "请输入有效的邮箱格式（如：xxx@qq.com）";
                },
                verifyPwdLength: function (value) {
                    if (value.length > 0 && value.length < 6) return "授权码长度不能少于6个字符";
                },
                verifySort: function (value) {
                    const sort = parseInt(value);
                    if (isNaN(sort) || sort < 0) return "请输入非负整数作为排序号（如：0、1、10）";
                }
            });

            // 3. 检查数据是否变更（核心：对比初始数据与当前数据）
            function isDataChanged(currentData) {
                // 对比常规字段（排除授权码）
                const compareFields = ['name', 'email_host', 'email_port', 'email_user', 
                                     'use_ssl', 'is_default', 'is_active', 'sort_num'];
                for (let field of compareFields) {
                    if (initialData[field] !== currentData[field]) {
                        return true; // 字段值有变更
                    }
                }

                // 授权码：非空则视为变更（空值表示不更新）
                if (currentData.email_password && currentData.email_password.trim().length > 0) {
                    return true;
                }

                return false; // 无变更
            }

            // 4. 表单提交事件（处理IntegerField类型转换）
            form.on('submit(email-config-save)', function (data) {
                const currentData = data.field;

                // 检查是否有变更
                if (!isDataChanged(currentData)) {
                    layer.msg("未修改任何数据，无需提交", { icon: 3, time: 1500 });
                    return false;
                }

                // 处理提交数据（关键：转换为Integer类型，适配后端模型）
                const submitData = {
                    ...currentData,
                    email_port: parseInt(currentData.email_port), // 端口转整数
                    use_ssl: parseInt(currentData.use_ssl), // 转为Integer（1/0）
                    is_default: parseInt(currentData.is_default), // 转为Integer（1/0）
                    is_active: parseInt(currentData.is_active), // 转为Integer（1/0）
                    sort_num: parseInt(currentData.sort_num) // 排序号转整数
                };

                // // 授权码为空则删除字段（避免覆盖原有值）
                // if (!submitData.email_password || submitData.email_password.trim() === '') {
                //     delete submitData.email_password;
                // }

                // 发送更新请求
                const loading = layer.load(2, { shade: 0.3 });
                $.ajax({
                    url: `${API_BASE_URL}/email/config/${CONFIG_ID}/`, // 统一接口前缀
                    data: JSON.stringify(submitData),
                    dataType: 'json',
                    contentType: 'application/json',
                    type: 'PATCH',
                    headers: { "Authorization": AUTH_TOKEN },
                    success: function (result) {
                        layer.close(loading);
                        if (result.success) {
                            layer.msg(result.message || '配置更新成功', {
                                icon: 1,
                                time: 1500
                            }, function () {
                                parent.layer.close(parent.layer.getFrameIndex(window.name));
                                parent.layui.table.reload("base-table"); // 刷新列表页表格
                            });
                        } else {
                            const errorMsg = result.message || '更新失败';
                            if (result.data && typeof result.data === 'object') {
                                const firstError = Object.values(result.data)[0];
                                layer.msg(firstError || errorMsg, { icon: 2, time: 2000 });
                            } else {
                                layer.msg(errorMsg, { icon: 2, time: 2000 });
                            }
                        }
                    },
                    error: function (xhr) {
                        layer.close(loading);
                        const errorMsg = xhr.status === 401 ? '登录已过期，请重新登录' : '网络异常，更新失败';
                        layer.msg(errorMsg, { icon: 2, time: 2000 });
                        if (xhr.status === 401) parent.window.location.href = '../../../login.html';
                    }
                });

                return false;
            });

            // 5. 关闭按钮
            $('#close-btn').on('click', function() {
                parent.layer.close(parent.layer.getFrameIndex(window.name));
            });
        });
    </script>
</body>
</html>